var vm,
	mixin = {},
	vm_data = {
		'account': {},
		'store': {},
		'room': {},
		'list': {}
	};

(function () {
	'use strict';
	var cache = {},
		
		// Dom
		$body,
		$container,
		$navi,
		$content,

		// Variables
		fadeSeed = 300,
		
		// State
		useCache = true, // SVG Caches
		isHome = false,
		isMoblie,
		isAjax = false;

	// Events
	var events = $({});

	$.subscribe = function() {
		events.on.apply(events, arguments);
	};

	$.unsubscribe = function() {
		events.off.apply(events, arguments);
	};

	$.publish = function() {
		events.trigger.apply(events, arguments);
	};

	function get(url, cb) {
		if (cache[url]) return cb(cache[url]);
		$.ajax({
			url: url,
			success: function(data) {
				cache[url] = data;
				cb(data);
			},
			error: function(jqXHR, textStatus, errorThrown) {
				console.log(jqXHR, textStatus, errorThrown);
			},
			dataType: 'text'
		});
	}

	function hanadle() {
		isHome = $body.hasClass('home');

		if ($body.find('.js-ui-loop').length !== 0) {
			loopRooms($body.find('.js-ui-loop'));
		}
		
		if ($body.find('.js-loop-store').length !== 0) {
			loopStore($body.find('.js-loop-timer'));
		}
		
		$body.find('[data-toggle="tooltip"]').tooltip();

		if ($body.find('.js-validate').length !== 0) {
			validates($body.find('.js-validate'));
		}

		if ($body.find('.js-svg').length !== 0) {
			svg($body.find('.js-svg'));
		}

		if ($body.find('.js-drop').length !== 0) {
			drop($body.find('.js-drop'));
		}

		if ($body.find('.js-ui-select').length !== 0) {
			uiSelects($body.find('.js-ui-select'));
		}

		if ($body.find('.js-datetimer').length !== 0) {
			datetimer($body.find('.js-datetimer'));
		}
		
		vm = new Vue({
			el: '#js-vue',
			mixins: [mixin],
			data: vm_data,
			directives: {
				svg:  {
					bind: function () {
						svg($(this.el));
					}
				},
				timerange:  {
					bind: function () {
						var $e = $(this.el);
					
						$e.daterangepicker({
							timePicker: true,
							timePickerIncrement: 5,
							showClassname: 'ui-timerange',
							autoUpdateInput: false,
							locale: {
								format: 'h:mm A',
								separator: ' - ',
								applyLabel: '应用',
								cancelLabel: '取消'
							}
						});
						
						$e.on('apply.daterangepicker', function(ev, picker) {
							$e.val(picker.startDate.format('h:mm A') + ' - ' + picker.endDate.format('h:mm A'));
						});

						$e.on('cancel.daterangepicker', function(ev, picker) {
							$e.val('');
						});
					}
				}

			},
			ready: function () {
				setTimeout(function() {
					$.publish('vuejs.ready', true);
				}, 10);
			}
		});
	}

	function init() {
		$body = $('body');
		$container = $('#wrap');
		$navi = $('#navi');
		$content = $body;
		isMoblie = _isMoblie();
		isHome = $body.hasClass('home');
		
		binedEvents();
		hanadle();
	}

	// Functions
	function _isMoblie(opts) {
		var userData = navigator.userAgent,
		opts = opts ? new RegExp(opts, 'i') : /iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle/i;
		return opts.test(userData);
	}

	function svg($svg) {
		$svg.each(function(){
			var $img = $(this);
			var imgID = $img.attr('id');
			var imgClass = $img.attr('class');
			var imgURL = $img.attr('src');

			if (localStorage.getItem(imgURL) !== null && useCache) {
				$svg = $(localStorage.getItem(imgURL));
				$img.replaceWith($svg);
			} else {
				$.get(imgURL, function(data) {
					var $svg = $(data).find('svg');
					if(typeof imgID !== 'undefined') {
						$svg = $svg.attr('id', imgID);
					}

					if(typeof imgClass !== 'undefined') {
						$svg = $svg.attr('class', imgClass+' replaced-svg');
					}

					$svg = $svg.removeAttr('xmlns:a');
					localStorage.setItem(imgURL, $('<div>').append($svg).html());
					$img.replaceWith($svg);

				}, 'xml');
			}
		});
	}

	function uiSelect($e) {
		var $this = $e,
			numberOfOptions = $this.children('option').length;

		$this.addClass('s-hidden');
		$this.wrap('<div class="ui-select-item"></div>');
		$this.after('<div class="ui-select"></div>');

		var $styledSelect = $this.next('div.ui-select');
		$styledSelect.text($this.children('option').eq(0).text());

		var $list = $('<ul />', {
			'class': 'options'
		}).insertAfter($styledSelect);

		for (var i = 0; i < numberOfOptions; i++) {
			$('<li />', {
				text: $this.children('option').eq(i).text(),
				rel: $this.children('option').eq(i).val()
			}).appendTo($list);
		}

		var $listItems = $list.children('li');

		$styledSelect.on('click', function (e) {
			e.stopPropagation();
			
			if ($(this).hasClass('active')) {
				$styledSelect.text($(this).text()).removeClass('active');
				$styledSelect.parents('.ui-select-item').removeClass('show');
				$this.val($(this).attr('rel'));
				$list.hide();
			} else {
				$('div.ui-select.active').each(function () {
					$(this).removeClass('active').next('ul.options').hide();
					$(this).parents('.ui-select-item').removeClass('show');
				});
				$(this).toggleClass('active').next('ul.options').toggle();
				$(this).parents('.ui-select-item').toggleClass('show');
			}
			

		});

		$listItems.on('click', function (e) {
			e.stopPropagation();
			$styledSelect.text($(this).text()).removeClass('active');
			$styledSelect.parents('.ui-select-item').removeClass('show');
			$this.val($(this).attr('rel'));
			$list.hide();
		});

		$(document).on('click', function () {
			$styledSelect.removeClass('active');
			$styledSelect.parents('.ui-select-item').removeClass('show');
			$list.hide();
		});
	}

	function uiSelects($eles) {
		$eles.each(function(){
			uiSelect($(this));
		});
		
	}

	function validates($form) {
		var	unhighlight = function (label, element) {
				$(element).closest('.input, .input-group').removeClass('has-error');
			},

			success = function (label, element) {
				label.addClass('help-block valid');
				$(element).closest('.input, .input-group').removeClass('has-error').addClass('has-success');
			},
			
			highlight = function (element) {
				$(element).closest('.help-block').removeClass('valid');
				$(element).closest('.input, .input-group').removeClass('has-success').addClass('has-error');
			},


			reset = function(els) {
				els[0].reset();
				els.find('.help-block').addClass('valid').html('');
				els.find('.input, .input-group').removeClass('has-success has-error').find('.symbol').removeClass('ok required');
			};

		$form.each(function() {
			var $currentForm = $(this);

			$currentForm.validate({
				errorElement: 'span',
				errorClass: 'help-block',
				ignore: '',
				unhighlight: unhighlight,
				success: success,
				highlight: highlight,
				submitHandler: function(form) {
					if ($(form).data('ajaxNextStep')) {
						var current = $(form).attr('action');
						var next = (Number(current) + 1);

						if (!$(form).data('ajaxNextDone')) {
							$body.scrollTop(0).find('.js-next-steps').removeClass('current-step-1 current-step-2 current-step-3 current-step-4 current-step-5 current-step-6 current-step-7 current-step-8').addClass('current-step-' + next);
						} else {
							alert('post form!')
						}
						
						return false;
					}

					if ($(form).data('ajaxNext')) {
						var current = $(form).attr('action');
						var next = (Number(current) + 1);

						if (next === 5) {
							$('#js-data-result').modal('show');
							var data = getFormData($body.find('.create-account-content form'));
							
							vm.$set('account', data);
							console.log(data);
						} else {
							$body.scrollTop(0).find('.create-account-content').removeClass('current-step-1 current-step-2 current-step-3 current-step-4').addClass('current-step-' + next);
						}
						
						return false;
					} else {
						form.submit();
					}
				}
			});
		});

		return {
			reset: reset
		}
	}

	function getFormData($forms) {
		var obj = {},
			key_name;

		$forms.each(function(index) {
			var data = $(this).serializeArray(); 
			$.each(data, function (i, field) { 
				key_name = field.name.replace('[]','');
				if (typeof obj[key_name] == 'undefined' && field.name.indexOf('[]') !== -1) obj[key_name] = [];
				if ( field.name.indexOf('[]') !== -1) { obj[key_name].push(field.value); } else {obj[key_name] = field.value;}
			});
		});

		return obj;
	}
	
	function datetimer($ele) {
		$ele.each(function() {
			var $e = $(this);
			
			$e.daterangepicker({
				timePicker: true,
				timePickerIncrement: 5,
				timePickerSeconds: true,
				timePicker24Hour: true,
				singleDatePicker: true,
				autoUpdateInput: false,
				showClassname: 'ui-datepicker',
				locale: {
					format: 'YYYY-MM-DD HH:mm:ss',
					applyLabel: '应用',
					cancelLabel: '取消'
				}
			});
			
			$e.on('apply.daterangepicker', function(ev, picker) {
				$e.val(picker.startDate.format('YYYY-MM-DD HH:mm:ss'));
			});

			$e.on('cancel.daterangepicker', function(ev, picker) {
				$e.val('');
			});
			
		});
	}

	function drop($ele) {
		$ele.each(function() {
			dragula([$(this).get(0)])
				.on('drag', function (el) {
					// el.className = el.className.replace('ex-moved', '');
				})
				.on('drop', function (el) {
					// el.className += ' ex-moved';
				})
				.on('over', function (el, container) {
					// console.log('over');
					// container.className += ' ex-over';
				})
				.on('out', function (el, container) {
					console.log('update here.')
					// container.className = container.className.replace('ex-over', '');
				});
		});
	}
	
	function loopRooms($ele) {
		var vm_data_rooms = {
			floors: [{
				rooms: [{
					is_init: true,
					is_edit: true,
					name: '',
					quantity: 0
				}]
			}]
		};

		mixin = {
			methods: {
				addFloor: function () {
					this.room.floors.push({
						rooms: [{
							is_init: true,
							is_edit: true,
							name: '',
							quantity: ''
						}]
					});
				},
				
				removeFloor: function (floor) {
					this.room.floors.$remove(floor);
				},
				
				
				editRoom: function (data, event) {
					data.is_edit = true;
				},

				updateRoom: function (floor, room, event) {
					var name = $(event.target).parents('.room-item').find('.input_name').val();
					var quantity = Math.floor(Number($(event.target).parents('.room-item').find('.input_quantity').val()));
					var index = $(event.target).parents('.room-item').data('index');
					
					if (!name) {
						alert('房间名不能为空');
						return false;
					}
					else if (!quantity || quantity < 1) {
						alert('床位名不能为空，且必须为数字, 数字需要大于0。');
						return false;
					}
					else {
						room.name = name;
						room.quantity = quantity;
						room.is_edit = false;
						
						if (room.is_init) {
							room.is_init = false;

							floor.rooms.push({
								is_init: true,
								is_edit: true,
								name: '',
								quantity: ''
							});
						}
					}
				},
				
				removeRoom: function (floor, room, event) {
					floor.rooms.$remove(room);
				}
			}
		}

		$.subscribe('vuejs.ready', function (ev, ele) {
			vm.$set('room', vm_data_rooms);
		});
	}
	
	function loopStore($ele) {
		var vm_data_stores = {
			timer: [''],
			contacts : [
				{
					name: '',
					phone: ''
				}
			]
		};
		
		mixin = {
			methods: {
				addTime: function () {
					this.store.timer.push({});
				},
				
				removeTime: function (timer) {
					this.store.timer.$remove(timer);
				},
				addContact: function () {
					this.store.contacts.push({});
				},
				
				removeContact: function (item) {
					this.store.contacts.$remove(item);
				}
			}
		}

		$.subscribe('vuejs.ready', function (ev, ele) {
			vm.$set('store', vm_data_stores);
		});
	}

	function binedEvents() {
		$body
			.on('focus', '.input-group input', function() {
				$(this).parents('.input-group').addClass('focus');
			})
			
			.on('blur', '.input-group input', function() {
				$(this).parents('.input-group').removeClass('focus');
			})
			
			.on('click', '.js-less', function() {
				var $input = $(this).parents('.input-num').find('input');
				
				if ($input.val() <= 1) {
					alert('最少数量为1');
				} else {
					$input.val($input.val() - 1);
				}
			})
			
			.on('click', '.js-plus', function() {
				var $input = $(this).parents('.input-num').find('input');
				
				if ($input.val() >= 99) {
					alert('最大数量为99');
				} else {
					$input.val(Number($input.val()) + 1);
				}
			})
			
			.on('click', '.js-ajax-prev', function() {
				var current = $(this).parents('form').attr('action');
				var prev = (Number(current) - 1);
				$body.scrollTop(0).find('.js-next-steps').removeClass('current-step-1 current-step-2 current-step-3 current-step-4 current-step-5 current-step-6 current-step-7 current-step-8').addClass('current-step-' + prev);
				return false;
			})

			.on('change', '.checkbox-list .js-all input[type=checkbox]', function() {
				var $current = $(this);
				var $inputs = $(this).parents('.checkbox-list').find('input[type=checkbox]');
				if ($current.prop('checked')) {
					$inputs.each(function() {
						$(this).prop('checked', true);
					});
					$current.addClass('has-all');
				} else {
					$inputs.each(function() {
						$(this).prop('checked', false);
					});
					$current.removeClass('has-all');
				}
			})
			.on('change', '.checkbox-list p input[type=checkbox]', function() {
				var $current = $(this);
				var $input = $(this).parents('.checkbox-list').find('.js-all input[type=checkbox]');
				if (!$current.prop('checked') && $input.hasClass('has-all')) {
					$input.removeClass('has-all').prop('checked', false);
				}
			})
			.on('change', '.js-checkbox-open input[type=checkbox]', function() {
				var $current = $(this).parents('.js-checkbox-open');
				if (!$(this).prop('checked')) {
					$current.removeClass('has-open');
				} else {
					$current.addClass('has-open');
				}
			})
			.on('change', '.js-preview-image input[type=file]', function() {
				var $current = $(this).parents('.js-preview-image');

				if ($(this).val() !== '') {
					var file = $(this).val();
					var extension = file.split('.').pop().toUpperCase();
					if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG" && extension!="BMP"){
						alert('请上传.jpg .jpeg .png .bmp格式照片');
						return false;
					}
				
					var reader = new FileReader();
					reader.onload = function (e) {
						$current.find('img')[0].src = e.target.result;
					};
					reader.readAsDataURL(this.files[0]);
					$current.addClass('active');
				} else {
					$current.removeClass('active');
				}

			});
	}
	
	$(document).ready(function () {
		$('.js-ui-filter').tipuedrop();

		init();
	});
}());

// Toto: move to libs.min.js
jQuery.validator.addMethod('stringCheck', function(value, element) {
	return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
}, '只能包括中文字，英文字母和数字'); 

$.validator.addMethod('isIdCardNo', function (value, element) {
	return this.optional(element) || isIdCardNo(value);
}, '请正确输入您的身份证号码');

jQuery.validator.addMethod('isMobile', function(value, element) {
	var length = value.length;
	var mobile = /^(((1[0-9]{2})|(15[0-9]{1}))+\d{8})$/;
	return this.optional(element) || (length == 11 && mobile.test(value));
}, '请正确填写您的手机号码');

jQuery.validator.addMethod('isTel', function(value, element) {
	//e.g. 010-12345678
	var tel = /^\d{3,4}-?\d{7,9}$/;
	return this.optional(element) || (tel.test(value));
}, '请正确填写您的电话号码');


jQuery.validator.addMethod('isPhone', function(value,element) {
	// Mobile + Tel
	var length = value.length;
	var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/;
	var tel = /^\d{3,4}-?\d{7,9}$/;
	return this.optional(element) || (tel.test(value) || mobile.test(value));
}, '请正确填写您的联系电话');

jQuery.validator.addMethod("isZipCode", function(value, element) {
	var tel = /^[0-9]{6}$/;
	return this.optional(element) || (tel.test(value));
}, '请正确填写您的邮政编码');


function isIdCardNo(num) {
	var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
	var parityBit = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
	var varArray = new Array();
	var intValue;
	var lngProduct = 0;
	var intCheckDigit;
	var intStrLen = num.length;
	var idNumber = num;

	if ((intStrLen != 15) && (intStrLen != 18)) {
		return false;
	}

	for (i = 0; i < intStrLen; i++) {
		varArray[i] = idNumber.charAt(i);
		if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
			return false;
		} else if (i < 17) {
			varArray[i] = varArray[i] * factorArr[i];
		}
	}

	if (intStrLen == 18) {
		var date8 = idNumber.substring(6, 14);
		if (isDate8(date8) == false) {
			return false;
		}

		for (i = 0; i < 17; i++) {
			lngProduct = lngProduct + varArray[i];
		}

		intCheckDigit = parityBit[lngProduct % 11];

		if (varArray[17] != intCheckDigit) {
			return false;
		}
	} else {
		var date6 = idNumber.substring(6, 12);
		if (isDate6(date6) == false) {
			return false;
		}
	}
	return true;
}

function isDate6(sDate) {
	if (!/^[0-9]{6}$/.test(sDate)) {
		return false;
	}
	var year, month, day;
	year = sDate.substring(0, 4);
	month = sDate.substring(4, 6);
	if (year < 1700 || year > 2500) return false
	if (month < 1 || month > 12) return false
	return true
}

function isDate8(sDate) {
	if (!/^[0-9]{8}$/.test(sDate)) {
		return false;
	}
	var year, month, day;
	year = sDate.substring(0, 4);
	month = sDate.substring(4, 6);
	day = sDate.substring(6, 8);
	var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
	if (year < 1700 || year > 2500) return false
	if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1] = 29;
	if (month < 1 || month > 12) return false
	if (day < 1 || day > iaMonthDays[month - 1]) return false
	return true
}


(function($) {
	 $.fn.tipuedrop = function(options) {
		var set = $.extend( {
			'show' : 3,
			'speed': 300
		}, options);
		
		return this.each(function() {
			var col = $('<div class="search_drop_box"></div>');
			$(this).after(col);

			var search_in = [];
			var list = $(this).find('.js-search-el');
			var input = $(this).find('.search_input');

			$(this).find('.js-search-el').each(function() {
				var data = {
					key : $(this).data('searchKey'),
					el: $(this),
					index : $(this).index()
				};

				search_in.push(data);
			});

			input.on('keyup focus', function(event) {
				getTipuedrop(input);
			}); 

			function getTipuedrop($obj) {
				if ($obj.val()) {
					var c = 0;
					for (var i = 0; i < search_in.length; i++) {
						var pat = new RegExp($obj.val(), 'i');
						if (search_in[i].key.search(pat) != -1 && c < set.show) {
							if (c == 0) {
								var out = '<ul>';
							}

							out += '<li class="js-search-item" data-for="' + search_in[i].index + '">' + search_in[i].key + '</li>';
							c++;
						}
					}

					if (c != 0) {
						out += '</ul>'; 
						col.html(out);
						col.fadeIn(set.speed);
					}
				} else {
					 col.fadeOut(set.speed);
				}
			}


			$(document).on('click', function() {
				col.fadeOut(set.speed);
			});
		});
	 };
	 
})(jQuery);
